package ar.edu.unicen.exa.isistan.archassis.view.dialogs;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import ar.edu.unicen.exa.isistan.archassis.view.Application;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.layout.FillLayout;

public abstract class AbstractWorkingDialog<V> extends Dialog {

	protected Future<V> result;
	protected ExecutorService executor;
	protected Shell shell;

	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public AbstractWorkingDialog(Shell parent, int style) {
		super(parent, style);
		setText(Application.APPLICATION_NAME + " | Cargando");
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public V open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		
		result = executeAction();
		
		while ((!shell.isDisposed()) && (!result.isDone()) ){
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		if (!shell.isDisposed()) {
			shell.dispose();
		}
		
		try {
			V r = result.get();
			executor.shutdown();
			return r;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), getStyle());
		shell.setSize(474, 78);
		shell.setText(getText());
		shell.setLayout(new FillLayout(SWT.VERTICAL));
		
		Label lblTrabajando = new Label(shell, SWT.NONE);
		lblTrabajando.setText(getTextInfo());
		
		ProgressBar progressBar = new ProgressBar(shell, SWT.INDETERMINATE);

		//table.get
//		result = executeAction();
		//ModelManager.getInstance().setClassesList(result);
//		exitAction(true);
	}

	protected Future<V> executeAction() {
		Callable<V> callable = createCallable();

		executor = new ScheduledThreadPoolExecutor(5);
		Future<V> future = executor.submit(callable);
		executor.shutdown();
		return future;

	}
	protected abstract Callable<V> createCallable();
	protected abstract String getTextInfo();
	
	protected void exitAction(boolean b) {
		shell.dispose();
	}
}
